package com.itxiao.service.impl;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.code.kaptcha.Producer;
import com.itxiao.config.RedisKeyConfig;
import com.itxiao.dao.SysUserDao;
import com.itxiao.dao.UserDao;
import com.itxiao.entity.SysUser;
import com.itxiao.entity.User;
import com.itxiao.pojo.bo.SysUserLoginBo;
import com.itxiao.pojo.dto.LoginBo;
import com.itxiao.pojo.vo.R;
import com.itxiao.pojo.vo.VerifyVo;
import com.itxiao.service.LoginService;
import com.itxiao.util.AliSmsUtil;
import com.itxiao.util.JwtUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Author xjy
 * @Date 2025/9/29 16:15
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Resource
    private SysUserDao dao;
    @Resource
    private UserDao userDao;
    @Resource
    private StringRedisTemplate template;
    @Resource
    private Producer captchaProducer; // Kaptcha 生产者

    @Override
    public R login(SysUserLoginBo bo) {
        //1.校验
        if (bo != null) {
            //2.查询
            LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<SysUser>();
            wrapper.or().eq(SysUser::getPhone, bo.getUsername());
            SysUser user = dao.selectOne(wrapper);
            //3.校验 用户是否存在
            if (Objects.nonNull(user)) {
                //4.校验是否已在线
                //5.校验密码
                if (user.getPassword().equals(bo.getPassword())) {
                    //6.账号校验成功 生成令牌
                    user.setPassword("");
                    String json = JSON.toJSONString(user);
                    String token = JwtUtil.createJwt(json);
                    //7.存储到Redis 1.有效期 30分钟空闲时间 2.什么数据类型 3.存储什么数据 4.数据同步
                    template.opsForValue().set(RedisKeyConfig.AUTH_LOGIN_TOKEN + token, json, 30, TimeUnit.MINUTES);
                    Map<String, Object> data = new HashMap<>();
                    data.put("token", token);
                    data.put("userId", user.getId());
                    return R.ok(data);
                }
            } else {
                return R.fail("账号密码错误！！！");
            }
        }
        return R.fail("亲，账号或密码不正确！");
    }

    @Override
    public R getVerify() throws IOException {
        // 1. 生成验证码文本
        String captchaText = captchaProducer.createText();
        System.out.println("生成的验证码: " + captchaText);

        // 2. 生成图片
        BufferedImage image = captchaProducer.createImage(captchaText);

        // 3. 将图片转为 Base64 编码的字符串
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", baos);
        byte[] imageBytes = baos.toByteArray();
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);
        String dataUri = "data:image/jpg;base64," + base64Image;
        String verifyUuid = UUID.randomUUID().toString();
        template.opsForValue().set(
                "captcha:" + verifyUuid,
                captchaText,
                60, TimeUnit.SECONDS
        );
        return R.ok(new VerifyVo(dataUri, verifyUuid));
    }

    @Override
    public R sendCode(String phone) {
        if ("".equals(phone)) {
            return R.fail("手机号不可为空");
        }
        //2.查询
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>();
        wrapper.or().eq(User::getPhone, phone);
        User user = userDao.selectOne(wrapper);
        //3.校验 用户是否存在
        if (Objects.isNull(user)) {
            return R.fail("用户不存在");
        }
        String code = template.opsForValue().get(RedisKeyConfig.SEND_CODE + phone);
        if ("".equals(code)) {
            return R.fail("已经发送过验证码");
        }
      //  AliSmsUtil.sendSms("17630951343",123456);
        template.opsForValue().set(
                RedisKeyConfig.SEND_CODE + phone, "123456",
                60 * 5, TimeUnit.SECONDS
        );
        return R.ok();
    }

    @Override
    public R userLogin(LoginBo bo) {
        String code = template.opsForValue().get(RedisKeyConfig.SEND_CODE + bo.getPhone());
        if (!bo.getCode().equals(code)) {
            return R.fail("验证码不正确");
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>();
        wrapper.or().eq(User::getPhone, bo.getPhone());
        User user = userDao.selectOne(wrapper);
        //3.校验 用户是否存在
        if (Objects.isNull(user)) {
            return R.fail("用户不存在");
        }
        user.setPassword("");
        String json = JSON.toJSONString(user);
        String token = JwtUtil.createJwt(json);
        template.opsForValue().set(RedisKeyConfig.AUTH_LOGIN_TOKEN + token, json, 60 * 60, TimeUnit.MINUTES);

        return R.ok(token);
    }
}
